package br.slic.jsf;

import java.io.IOException; 
import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.slic.entidade.UsuarioSistema;
import br.slic.exception.ServiceException;
import br.slic.exception.UsuarioInexistente;
import br.slic.services.interfaces.AdminServiceLocal;
import br.slic.util.SLICWebConstantes;

@ManagedBean
@SessionScoped
public class LoginBean {

	private ResourceBundle bundle = ResourceBundle.getBundle("mensagens");
	private UsuarioSistema usuarioSistema = new UsuarioSistema();
	
	@EJB
	private AdminServiceLocal adminService;

	public void entrar() {  
        FacesMessage msg = null;
        try {
			usuarioSistema = adminService.obterUsuario(usuarioSistema.getLogin(), usuarioSistema.getSenha());
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
			session.setAttribute(SLICWebConstantes.SESSAO_USUARIO, usuarioSistema);
			FacesContext.getCurrentInstance().getExternalContext().redirect(SLICWebConstantes.PAGINA_INICIAL);
		} catch (UsuarioInexistente e) {
			msg = new FacesMessage(FacesMessage.SEVERITY_WARN, bundle.getString("invalido_login"), "");  
		} catch (ServiceException e) {
			msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
		} catch (IOException e) {
			msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
		}
        if( msg != null ) {
        	FacesContext.getCurrentInstance().addMessage(null, msg);
        }
	}

	public void sair() {
        FacesMessage msg = null;
        try {
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
			session.invalidate();
			FacesContext.getCurrentInstance().getExternalContext().redirect(SLICWebConstantes.PAGINA_LOGIN);
		} catch (IOException e) {
			msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
		}
        if( msg != null ) {
        	FacesContext.getCurrentInstance().addMessage(null, msg);
        }		
	}
	
	/**
	 * @return the usuarioSistema
	 */
	public UsuarioSistema getUsuarioSistema() {
		return usuarioSistema;
	}

	/**
	 * @param usuarioSistema the usuarioSistema to set
	 */
	public void setUsuarioSistema(UsuarioSistema usuarioSistema) {
		this.usuarioSistema = usuarioSistema;
	}
	
}
